package com.itheiam.servlet;


import com.itheiam.service.DemoService;
import com.itheiam.service.impl.DemoServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

//自定义一个处理类
public class BaseServlet extends HttpServlet {
    public DemoService demoService;
    @Override
    public void init() throws ServletException {
        demoService = new DemoServiceImpl();
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        //获取方法名
        String methodName = uri.substring(uri.lastIndexOf("/") + 1);
        //获取执行的目标对象
        //System.out.println(this);
        try {
            //获取执行的方法对象
            Method method =
                    this.getClass().getDeclaredMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
            //暴力反射
            method.setAccessible(true);
            //执行目标方法
            method.invoke(this,req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
